import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Pagination, Grid } from 'semantic-ui-react'
import { Query } from 'react-apollo'
import { listTable as listTableDuck } from 'ducks'
import produce from 'immer'
import Loading from './loading'

class PaginationData extends Component {
  componentWillUnmount = () => {
    const { actionReset } = this.props
    actionReset()
  }

  render() {
    const {
      children,
      query,
      pageInfo,
      queryName,
      actionReciveData,
      actionNumPage,
      variables,
      searchInfo,
      search,
    } = this.props

    const variablesFinal = produce(variables, (draftState) => {
      if (search) draftState.search = searchInfo ? `%${searchInfo}%` : '%%'
    })

    return (
      <Query
        query={query}
        fetchPolicy="network-only"
        variables={variablesFinal}
        onCompleted={(data) => {
          const { count } = data[queryName].aggregate
          const pages = Math.ceil(count / pageInfo.limit)
          actionReciveData(pages)
          actionNumPage(1)
        }}
      >
        {({ loading, error, data }) => {
          if (loading) return <Loading />
          if (error) return `Error! ${error.message}`
          return (
            <React.Fragment>
              {children}
              <Grid.Column>
                {pageInfo.number > 5 && (
                  <Pagination
                    activePage={pageInfo.activeNum}
                    totalPages={pageInfo.number}
                    onPageChange={(e, { activePage }) => actionNumPage(activePage)}
                  />
                )}
                {pageInfo.number <= 5 && pageInfo.number > 1 && (
                  <Pagination
                    ellipsisItem={null}
                    firstItem={null}
                    lastItem={null}
                    prevItem={null}
                    nextItem={null}
                    siblingRange={1}
                    activePage={pageInfo.activeNum}
                    totalPages={pageInfo.number}
                    onPageChange={(e, { activePage }) => actionNumPage(activePage)}
                  />
                )}
              </Grid.Column>
            </React.Fragment>
          )
        }}
      </Query>
    )
  }
}

const mapStateToProps = state => ({
  pageInfo: listTableDuck.selectors.pageInfo(state),
  searchInfo: listTableDuck.selectors.searchInfo(state),
})

const mapDispatchToProps = {
  actionInit: listTableDuck.creators.actionInit,
  actionReset: listTableDuck.creators.actionReset,
  actionReciveData: listTableDuck.creators.actionReciveData,
  actionNumPage: listTableDuck.creators.actionNumPage,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(PaginationData)
